﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Casamiel.Application;
using MediatR;

using Casamiel.API.Infrastructure;
using Casamiel.API.Application.Commands;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;

using Casamiel.API.Application.Models;
using Casamiel.Domain.Response;
using Casamiel.API.Infrastructure.Filters;
using NLog;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// Activity controller.
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/[controller]")]
    [ApiController]
    [Authorize]

    public class ActivityController : Controller
    {
        private readonly IMediator _mediator;
        private readonly List<Casamiel.Domain.Entity.ActivityInfo> _activities;
        private readonly NLog.ILogger logger = LogManager.GetLogger("BizInfo");

        /// <summary>
        /// Initializes a new instance of the <see cref="T:Casamiel.API.Controllers.V2.ActivityController"/> class.
        /// </summary>
        /// <param name="mediator">Mediator.</param>
        /// <param name="optionsSnapshot">Options snapshot.</param>
        public ActivityController(IMediator mediator, IOptionsSnapshot<List<Casamiel.Domain.Entity.ActivityInfo>> optionsSnapshot)
        {
            if (optionsSnapshot == null) {
                throw new ArgumentNullException(nameof(optionsSnapshot));
            }

            _mediator = mediator;
            _activities = optionsSnapshot.Value;
        }
        /// <summary>
        /// Gets the activity.
        /// </summary>
        /// <returns>The activity.</returns>
        [HttpPost]
        [Route("[action]")]
        public ActionResult<BaseResult<ActivityInfoRsp>> GetActivity()
        {
            if (_activities.Any()) {
                var rsp = new ActivityInfoRsp {
                    Id = _activities[0].Id,
                    ActivityName = _activities[0].ActivityName,
                    BeginTime = _activities[0].BeginTime,
                    EndTime = _activities[0].EndTime,
                    Enable = _activities[0].Enable,
                    Total = _activities[0].Total,
                    Describe = _activities[0].Describe
                };
                return new BaseResult<ActivityInfoRsp>(rsp, 0, "");
            }
            return new BaseResult<ActivityInfoRsp>(null, -38, "活动不存在");
        }

        /// <summary>
        /// 领券列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public ActionResult<BaseResult<List<ActivityInfoRsp>>> GetActivityList()
        {
            if (_activities.Any()) {
                var list = _activities.Where(c => c.IsShow == true).ToList().OrderByDescending(c => c.Sort);
                var rsp = from x in list
                          select (new ActivityInfoRsp {
                              Id = x.Id,
                              ActivityName = x.ActivityName,
                              BeginTime = x.BeginTime,
                              EndTime = x.EndTime,
                              Enable = x.Enable,
                              Total = x.Total,
                              Describe = x.Describe
                         });

                return new BaseResult<List<ActivityInfoRsp>>(rsp.ToList(), 0, "");
            }
            return new BaseResult<List<ActivityInfoRsp>>(new List<ActivityInfoRsp>(), -38, "活动不存在");
        }
        /// <summary>
        /// 获取优惠卷
        /// </summary>
        /// <returns>The coupon.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<string>>> GetCoupon([FromBody] GetCouponReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            logger.Trace($"GetCoupon:{JsonConvert.SerializeObject(req)}");
            var mobile =   MemberHelper.GetMobile(token);
            var command = new CreateMemberCouponCommand(req.ActivityId, mobile);
            return await _mediator.Send(command).ConfigureAwait(false);
        }

        /// <summary>
        /// 检查是否领券
        /// </summary>
        /// <returns>The coupon.</returns>
        /// <param name="req">Req.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<bool>>> CheckCoupon([FromBody] GetCouponReq req, [FromHeader(Name = "u-token")] string token)
        {
            if (req == null) {
                throw new ArgumentNullException(nameof(req));
            }
            logger.Trace($"CheckCoupon:{JsonConvert.SerializeObject(req)}");
            var mobile = MemberHelper.GetMobile(token);
            var command = new CheckMemberCouponCommand(req.ActivityId, mobile);
            return await _mediator.Send(command).ConfigureAwait(false);
        }
    }
}
